﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SportClubMvc.Model;
using SportClubMvc.Model.SportsClubClasses;

namespace SportClubMvc.Controllers
{
    public class NewsController : Controller
    {
        private readonly SportsClubDbContext _dbContext = new SportsClubDbContext();

        public ActionResult AddNews()
        {
            ViewBag.Message = "Legg til nyhet";
            return View();
        }

        [HttpPost, ValidateInput(false)]
        public RedirectToRouteResult AddNews(NewsModel newsModel, HttpPostedFileBase file)
        {
            if (file != null)
            {
                var fileName = Path.GetFileName(file.FileName);
                if (fileName != null)
                {
                    var path = Path.Combine(Server.MapPath("~/Content/images/news"), fileName);
                    file.SaveAs(path);
                    newsModel.HeaderImagePath = fileName;
                }
            }

            newsModel.DateCreated = DateTime.Now;
            newsModel.Creator = User.Identity.IsAuthenticated ? User.Identity.Name : "Anonymous";
            
            _dbContext.News.Add(newsModel);
            _dbContext.SaveChanges();

            return RedirectToAction("Index", "Home");
        }

        public ActionResult Index(int id)
        {
            var newsItem = _dbContext.News.Where(x => x.Id == id).FirstOrDefault();
            return View(newsItem);
        }

        public ActionResult Edit(int id)
        {
            var newsItem = _dbContext.News.Where(x => x.Id == id).FirstOrDefault();

            return View(newsItem);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult Edit(NewsModel model)
        {
            var modelToUpdate = _dbContext.News.Where(x => x.Id == model.Id).FirstOrDefault();

            if (modelToUpdate != null)
            {
                _dbContext.Entry(modelToUpdate).CurrentValues.SetValues(model);
                _dbContext.SaveChanges();
            }
            return View("Index", model);
        }

        [HttpGet]
        public JsonResult GetRelatedNews(int id)
        {
            var listOfNews = _dbContext.News.ToList().Where(x => x.Id != id).Take(5);

            return new JsonResult
                       {
                           Data = new {Message = "Success", News = listOfNews},
                           JsonRequestBehavior = JsonRequestBehavior.AllowGet
                       };
        }

        public ActionResult Delete(int id)
        {
            var newsItem = _dbContext.News.Where(x => x.Id == id).FirstOrDefault();

            _dbContext.News.Remove(newsItem);
            _dbContext.SaveChanges();

            return RedirectToAction("Index", "Home");
        }
    }
}